/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

package com.huawei.api.handler;

import com.huawei.api.bean.CloudDefect;
import com.huawei.api.exception.BaseCustomerException;
import com.huawei.api.utils.ReportUtil;

import lombok.Data;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 报告处理
 *
 * @since 2023/10/28
 */
@Data
public class ReportHandler implements Handler {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReportHandler.class);

    private final String reportPath;

    private final List<CloudDefect> defects;

    public ReportHandler(String reportPath) {
        this.reportPath = reportPath;
        this.defects = new ArrayList<>();
    }

    @Override
    public void handle() throws BaseCustomerException {
        File file = new File(reportPath);
        if (!file.exists()) {
            LOGGER.debug("some error in report handler, report path is error, report path is: {}", reportPath);
            return;
        }
        //获取报告 （由于参数传的是report文件夹，需要去report文件夹下读取 .json文件结尾的）
        if (file.isFile()) {
            File[] files = file.listFiles();
            if (ObjectUtils.isEmpty(files)) {
                return;
            }
            for (File file1 : files) {
                if (file1.getName().endsWith(".json")) {
                    getDefects(file1);
                }
            }
        }
    }

    private void getDefects(File file) throws BaseCustomerException {
        try {
            String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
            this.defects.addAll(ReportUtil.getCloudDefectsByContent(content));
//            FileUtil.delFile(file);
        } catch (IOException exception) {
            LOGGER.error("some error in get defect, file is {}", file.getName());
            throw new BaseCustomerException("some error in get defects");
        }
    }
}
